<?php

namespace App\Http\Controllers;

use App\Models\Question;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use JPush\Client as JPush;

class QuestionController extends BaseController
{

    public function addQuestion(Request $request){
        $question=new Question;
        $question->title=$request->input('title');
        $question->description=$request->input('description');
        $question->content=$request->input('content');
        $question->userId=$request->input('userId');
        $question->file=$request->input('file');

        $user=User::find($question->userId);
        $client = new JPush("49a057407f2e5590104e6e01", "88a7d48da19c80b0c185c716");
        $client->push()
            ->setPlatform('all')
            ->addAllAudience()
            ->setNotificationAlert($user->name.'提问了 '.$question->title.' 问题')
            ->send();

        $question->save();



        $arr = array('status' => 'success', 'data' => $question->id);
        echo json_encode($arr);
    }

    public function getAllQuestions(){

        $questions=DB::table('question')         //将两张表拼接起来
        ->join('user', function($join)
        {
            $join->on('question.userId', '=', 'user.id');
        })->select('question.id', 'question.title','question.description','question.content',
            'question.file','user.name')
            ->get();
        $arr = array('status' => 'success', 'data' => $questions);
        echo json_encode($arr);
    }

    public function getOneQuestion(){
        $id=$_GET['id'];
        $question=DB::table('question')         //将两张表拼接起来
        ->where('question.id', $id)
        ->join('user', function($join)
        {
            $join->on('question.userId', '=', 'user.id');
        })->select('question.id', 'question.title','question.description','question.content',
            'question.file','user.name')
            ->get();
        $arr = array('status' => 'success', 'data' => $question);
        echo json_encode($arr);
    }

    public function save(Request $request){
        $file=$request->file('file');
        if ($file) {
            $name = $file->getClientOriginalName(); // 文件原名

            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg

            // 上传文件
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
            //var_dump($bool);
        }
        $arr = array('status' => 'success', 'data' => $filename);
        echo json_encode($arr);
    }
}
